#!/bin/sh
set -e

usage () {
    echo "usage: git sha [-sq] [<object>]" >&2
    echo >&2
    echo "Options:" >&2
    echo "-s    Output short SHAs" >&2
    echo "-q    Be quiet (only return exit code 0 when object exists)" >&2
    echo "-h    Show this help" >&2
    echo >&2
    echo "<object> defaults to HEAD"
}

short=0
quiet=0
while getopts sqh flag; do
    case "$flag" in
        s) short=1;;
        q) quiet=1;;
        h) usage; exit 2;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -eq 1 ]; then
    object=$1
else
    object="HEAD"
fi

opts=""
if [ $short -eq 1 ]; then
    opts="--short"
fi

set +e
output=$(git rev-parse $opts "$object" 2>/dev/null)
status=$?
set -e
if [ $status -ne 0 ]; then
    echo "Invalid object: '$object'" >&2
    exit 1
else
    if [ $quiet -eq 0 ]; then
        echo "$output"
    fi
    exit 0
fi
